#include "StdAfx.h"
#include "SimpleEncrypt.h"

namespace PPLiveLogClient
{

SimpleEncrypt::SimpleEncrypt(const char* pKey)
	: _key(pKey)
{
}

SimpleEncrypt::~SimpleEncrypt(void)
{
}

SimpleBinaryData SimpleEncrypt::Encrypt(const CStringA& input) const
{
	return SimpleEncrypt::EncryptImpl(input, PCSTR(this->_key), this->_key.GetLength());
}

/*static*/SimpleBinaryData SimpleEncrypt::Encrypt(const CStringA& input, const char* pKey, int keySize/*=-1*/)
{
	if (pKey == NULL)
	{
		return input;
	}

	if (keySize < 0)
	{
		keySize = ::strlen(pKey);
	}
	return SimpleEncrypt::EncryptImpl(input, pKey, keySize);
}

// very simple policy, just avoid raw text being seen without any effort.
/*static*/SimpleBinaryData SimpleEncrypt::EncryptImpl(const CStringA& input, const char* pKey, int keySize)
{
	if (pKey == NULL)
	{
		return input;
	}
	_ASSERT(::strlen(pKey) == keySize);

	SimpleBinaryData result;
	BYTE* p = result.GetBuffer(input.GetLength());
	for (int i = 0; i < input.GetLength(); ++i)
	{
		p[i] = input[i] + pKey[i % keySize];
	}
	result.ReleaseBuffer(input.GetLength());

	return result;
}

}

